<script setup lang="ts">
import styles from './HomeView.module.css'
import { ref, onMounted, computed, onUnmounted, watch } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
// @ts-ignore
import { getFavSet, saveFavSet } from './favStore'

// 商品接口定义（修正原代码中的大小写问题）
interface Product {
  _id: string
  name: string
  price: number
  description: string
  createdAt: Date
  colorx: Array<{ context: string }>
  chima: Array<{ context: string }>
  images: string // 改为 images
  category: string // 修正为小写
}

// 分类映射（补充完整分类）
const categoryNameMap: Record<string, string> = {
  electronics: '电子产品',
  clothing: '服装',
  home: '家居',
  books: '图书',
  beauty: '美妆',
  sports: '运动',
  accessories: '数码配件',
  food: '食品',
  appliances: '家电',
  stationery: '文具',
  bags: '箱包',
  baby: '母婴',
  car: '汽车用品',
  pets: '宠物用品',
  outdoor: '户外',
  toys: '玩具',
  office: '办公',
  music: '乐器',
  health: '保健品',
  crafts: '手工'
}

const router = useRouter()
const productList = ref<Product[]>([])
const selectedCategory = ref('全部')
const page = ref(1)
const pageSize = 6
const loading = ref(false)
const finished = ref(false)

// 计算属性：分类列表（自动从商品数据生成，全部用中文）
const categoryList = computed(() => {
  const categories = new Set<string>()
  productList.value.forEach(item => {
    if (item.category) categories.add(item.category)
  })
  return ['全部', ...Array.from(categories)]
})

// 当前显示的商品列表（带分类筛选，全部用中文）
const filteredProducts = computed(() => {
  if (selectedCategory.value === '全部') return productList.value
  return productList.value.filter(item => item.category === selectedCategory.value)
})

// 获取商品数据
const fetchProducts = async () => {
  if (loading.value || finished.value) return

  loading.value = true
  try {
    const params = {
      page: page.value,
      pageSize,
      category: selectedCategory.value !== '全部' ? selectedCategory.value : undefined
    }

    const response = await axios.get<{
      data: Product[]
      total: number
    }>('http://localhost:3000/YJL/waterlist', { params })

    // 将所有商品的 category 字段映射为中文
    const mappedData = response.data.data.map(item => ({
      ...item,
      category: categoryNameMap[item.category] || item.category
    }))

    if (page.value === 1) {
      productList.value = mappedData
    } else {
      productList.value.push(...mappedData)
    }

    // 检查是否已加载全部数据
    if (productList.value.length >= response.data.total) {
      finished.value = true
    } else {
      page.value++
    }
  } catch (error) {
    console.error('获取商品失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置分页并重新加载
const resetAndLoad = () => {
  page.value = 1
  finished.value = false
  fetchProducts()
}

// 跳转到详情页
const goDetail = (id: string) => {
  router.push({ name: 'xiangqing', query: { id } })
}

// 跳转到搜索页
const goSearch = () => {
  router.push('/search')
}

// 跳转到活动页
const goActivity = (id: number) => {
  router.push({ name: 'activity', query: { id } })
}

// 轮播图数据
const carouselImages = ref([
  { src: '/img/5.jpg', alt: '促销活动1', id: 1 },
  { src: '/img/car1.jpg', alt: '新品上市', id: 2 },
  { src: '/img/car2.jpg', alt: '限时折扣', id: 3 },
  { src: '/img/car5.jpg', alt: '会员专享', id: 4 }
])

// 轮播图逻辑
const currentIndex = ref(0)
let timer: number | undefined

const nextSlide = () => {
  currentIndex.value = (currentIndex.value + 1) % carouselImages.value.length
}

const startAutoPlay = () => {
  stopAutoPlay()
  timer = window.setInterval(nextSlide, 5000)
}

const stopAutoPlay = () => {
  if (timer) clearInterval(timer)
}


// 滚动加载更多
const homeRef = ref<HTMLElement | null>(null)
const handleScroll = (e: Event) => {
  const el = e.target as HTMLElement
  const { scrollTop, clientHeight, scrollHeight } = el

  // 滚动到底部时加载更多
  if (scrollTop + clientHeight >= scrollHeight - 10 && !loading.value && !finished.value) {
    fetchProducts()
  }
}

// 生命周期钩子
onMounted(() => {
  fetchProducts()
  startAutoPlay()
  favSet.value = getFavSet()
  homeRef.value?.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  stopAutoPlay()
  homeRef.value?.removeEventListener('scroll', handleScroll)
})

// 监听分类变化
watch(selectedCategory, () => {
  resetAndLoad()
})

const tabListRef = ref<HTMLDivElement | null>(null)

const dragState = ref({
  startX: 0,
  dragging: false
})

function onDragStart(e: MouseEvent | TouchEvent) {
  dragState.value.dragging = true
  dragState.value.startX = 'touches' in e ? e.touches[0].clientX : (e as MouseEvent).clientX
  stopAutoPlay()
}

function onDragMove(e: MouseEvent | TouchEvent) {
  if (!dragState.value.dragging) return
  const currentX = 'touches' in e ? e.touches[0].clientX : (e as MouseEvent).clientX
  const delta = currentX - dragState.value.startX
  if (Math.abs(delta) > 40) {
    if (delta > 0) {
      currentIndex.value = (currentIndex.value - 1 + carouselImages.value.length) % carouselImages.value.length
    } else {
      currentIndex.value = (currentIndex.value + 1) % carouselImages.value.length
    }
    dragState.value.dragging = false
    startAutoPlay()
  }
}

function onDragEnd() {
  dragState.value.dragging = false
  startAutoPlay()
}

function showAllProducts() {
  selectedCategory.value = '全部'
  resetAndLoad()
}

// 收藏状态
const favSet = ref(getFavSet())
function toggleFav(id: string) {
  if (favSet.value.has(id)) {
    favSet.value.delete(id)
  } else {
    favSet.value.add(id)
  }
  saveFavSet(favSet.value)
}
</script>

<template>
  <div ref="homeRef" :class="[styles.home, 'home-container']" style="height: 100vh; overflow-y: auto; -webkit-overflow-scrolling: touch;">

    <!-- 搜索栏 -->
    <div :class="styles.searchBar">
      <input :class="styles.searchInput" type="text" placeholder="🔍 搜索商品" readonly @click="goSearch" />
    </div>

    <!-- 轮播图 -->
    <div :class="styles.carousel">
      <div :class="styles.carouselImg" @mousedown="onDragStart" @mousemove="onDragMove" @mouseup="onDragEnd"
        @mouseleave="onDragEnd" @touchstart.passive="onDragStart" @touchmove.passive="onDragMove" @touchend="onDragEnd"
        style="position:relative;overflow:hidden;">
        <div :class="styles.carouselTrack" :style="{
          width: (carouselImages.length * 100) + '%',
          transform: `translateX(-${currentIndex * (100 / carouselImages.length)}%)`,
          transition: 'transform 0.5s cubic-bezier(.4,0,.2,1)'
        }">
          <img v-for="(img, idx) in carouselImages" :key="idx" :src="img.src" :alt="img.alt"
            :class="styles.slideImage" @click="goActivity(img.id)" style="cursor:pointer;" />
        </div>
      </div>
    </div>

    <!-- 热门商品区域 -->
    <div :class="styles.hotSection">
      <div :class="styles.hotHeader">
        <h2 :class="styles.hotTitle">热门商品</h2>
        <span :class="styles.hotMore" @click="showAllProducts">查看全部 &gt;</span>
      </div>

      <!-- 分类标签 -->
      <div :class="styles.hotTabs" ref="tabListRef">
        <button v-for="cat in categoryList" :key="cat"
          :class="[styles.hotTab, selectedCategory === cat ? styles.hotTabActive : '']" @click="selectedCategory = cat">
          {{ cat }}
        </button>
      </div>

      <!-- 商品网格 -->
      <div :class="styles.productGrid">
        <div v-for="product in filteredProducts" :key="product._id" :class="styles.productCard"
          @click="goDetail(product._id)">
          <div :class="styles.productImgBox">
            <img :src="product.images" :alt="product.name" :class="styles.productImg" loading="lazy" />
            <button :class="[styles.productFav, favSet.has(product._id) ? styles.favActive : '']" @click.stop="toggleFav(product._id)">
              <span v-if="favSet.has(product._id)">♥</span>
              <span v-else>♡</span>
            </button>
          </div>

          <div :class="styles.productTitle">{{ product.name }}</div>
          <p :class="styles.productDesc">{{ product.description }}</p>

          <div :class="styles.productInfoRow">
            <span :class="styles.productStar">★ 4.8</span>
            <span :class="styles.productSold">已售 {{ Math.floor(Math.random() * 5000) + 1000 }}</span>
          </div>

          <div :class="styles.productPrice">¥{{ product.price.toFixed(2) }}</div>

          <button :class="styles.addToCartBtn">
            加入购物车
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" :class="styles.loadingText">加载中...</div>
    <div v-if="finished && !loading" :class="styles.finishedText">没有更多了</div>

    <div :class="styles.bottomSpacer"></div>
  </div>
</template>
